package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.codehaus.xfire.XFireFactory;
//import org.codehaus.xfire.client.XFireProxyFactory;
//import org.codehaus.xfire.service.binding.ObjectServiceFactory;

import org.bminfo.migle.format.*;
import org.bminfo.migle.parser.Initialization;

public class InitializationServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public InitializationServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String filecontent = request.getParameter("sequence");
		String filetype = request.getParameter("filetype");
		String region = request.getParameter("region");
		
		Map<String, String> iupac = new HashMap<String,String>();
		iupac.put("A", "A");
		iupac.put("C", "C");
		iupac.put("G", "G");
		iupac.put("T", "T");
		iupac.put("M", "AC");
		iupac.put("R", "AG");
		iupac.put("W", "AT");
		iupac.put("S", "CG");
		iupac.put("Y", "CT");
		iupac.put("K", "GT");
		iupac.put("V", "ACG");
		iupac.put("H", "ACT");
		iupac.put("D", "AGT");
		iupac.put("B", "CGT");
		iupac.put("N", "ACGT");

//		org.codehaus.xfire.service.Service srvcModel = new ObjectServiceFactory()
//				.create(IMoopsServer.class);
//		XFireProxyFactory factory = new XFireProxyFactory(XFireFactory
//				.newInstance().getXFire());
//		String moopsServiceURL = "http://" + request.getServerName().toString()
//				+ ":" + request.getServerPort() + "/miGLE/services/MoopsServer";
//		IMoopsServer srvc = (IMoopsServer) factory.create(srvcModel,
//				moopsServiceURL);
		
		String miGLE_home = request.getSession().getServletContext().getRealPath("/");
		request.getSession().setAttribute("miGLE_home", miGLE_home);
		
		Initialization task = new Initialization();
		
		task.setmiGLEHome(miGLE_home);
				
		System.out.println("TOMCAT_HOME is " + miGLE_home);

		String folderName;
		String[] data = null;
		String startSeq = null;
		String endSeq = null;
		String seqfile = null;
		String range = null;
		String site = "";
		
		if(filetype.equals("fasta")){
			
			FASTA fa = new FASTA();
			data = fa.fastaParser(filecontent);

			seqfile = data[0];
			String length = data[1];

			folderName = task.initialization("seq.fasta", seqfile);
			
			range = "(Between 1 and " + length + ")";
			
			request.getSession().setAttribute("folderName", folderName);
			request.getSession().setAttribute("start", "1");
			request.getSession().setAttribute("range", range);
			request.getSession().setAttribute("seqfile", seqfile);
			request.getSession().setAttribute("filetype", filetype);
			request.getSession().setAttribute("site", site);
			
			response.sendRedirect("../pointmut.jsp");

		} else if(filetype.equals("snp")){
			
			SNP snp = new SNP();			
			data = snp.snpParser(filecontent);
    		
			folderName = task.initialization("seq.fasta", filecontent.replace("\r", ""));
			
			String head = data[0];
			String seq = data[1];
			int length = Integer.parseInt(data[2]);
			int site_num = Integer.parseInt(data[3]);
			String iupac_char = data[4];
			String snpclass = data[5];
			String snpstring = data[6];
			
			String[] allele = snpstring.split("/");
			
			StringBuilder print = new StringBuilder();
			
            for(int i=0; i<allele.length; i++){
    			
            	print.append("<table><tr>");
            	
    			if(i==0){
    				print.append("<input type=\"radio\" value=\"" + allele[i] + "\" name=\"point\" id=\"point\" checked />");
    			}else{
    				print.append("<input type=\"radio\" value=\"" + allele[i] + "\" name=\"point\" id=\"point\"/>");
    			}
    			
    			print.append("<strong>  Reference Sequence " + (i+1) + ":\t<span class=\"snp\">" + iupac_char + " to " + allele[i] + "</span></strong></tr>");        	        			
    			print.append("<tr><td>" + head + "\n" + "</td></tr>");
    			print.append("<tr><td><pre>");
    			print.append(new SeqFormatter().seqFormatter(seq.substring(0, site_num-1)) + "\n");
    			print.append("<span class=\"snp\">" + allele[i] + "</span>" + "\n");
    			print.append(new SeqFormatter().seqFormatter(seq.substring(site_num, length)) + "\n");
    			print.append("</pre></td></tr></table>");
            }
			
			request.getSession().setAttribute("folderName", folderName);
            request.getSession().setAttribute("head", data[0]);
			request.getSession().setAttribute("seq", data[1]);
			
			range = "(SNP site)";
			
			request.getSession().setAttribute("seqfile", filecontent);
			request.getSession().setAttribute("range", range);
			request.getSession().setAttribute("site", data[3]);		
			request.getSession().setAttribute("iupac_char", iupac_char);
			request.getSession().setAttribute("reference", print.toString());
			
			response.sendRedirect("../reference.jsp");
			
		} else {
			
			GenBank gb = new GenBank();
			data = gb.genbankParser(filecontent, region);
				
			startSeq = data[0];
			endSeq = data[1];
			seqfile = data[2];

			folderName = task.initialization("seq.fasta", seqfile);
			range = "(Between " + startSeq + " and " + endSeq + ")";
			
			request.getSession().setAttribute("folderName", folderName);
			request.getSession().setAttribute("start", startSeq);
			request.getSession().setAttribute("range", range);
			request.getSession().setAttribute("seqfile", seqfile);
			request.getSession().setAttribute("filetype", filetype);
			request.getSession().setAttribute("site", site);

			response.sendRedirect("../pointmut.jsp");
		}
		// System.out.println("Foldername in InitializationServlet is: " +
		// folderName);

//		RequestDispatcher rd = request.getRequestDispatcher("../pointmut.jsp");
//		rd.forward(request, response);

	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}
